package com.designoutput.manager
{
	import com.designoutput.manager.fontManagerClasses.FontStyleInfo;
	import com.designoutput.manager.fontManagerClasses.FontInfo;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFormat;

	public class FontManager
	{
		private const FONT_LIST_PATH:String = "config/xml/fonts.xml";
		
		private var _fontListLoadedCallback:Vector.<Function>;
		
		public var availableFonts:Vector.<FontInfo>;
				
		public function FontManager()
		{
			_fontListLoadedCallback = new Vector.<Function>();
			
			loadFontList();
		}
		
		private function loadFontList():void{
			var request:URLRequest = new URLRequest(/*Globals.applicationUrl + */FONT_LIST_PATH);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, fontListLoadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loadErrorHandler);
			loader.load(request);
		}
		
		private function loadErrorHandler(evt:IOErrorEvent):void{
			trace("Failed to load font list. " + evt.text);
		}
		
		private function fontListLoadComplete(evt:Event):void{
			availableFonts = new Vector.<FontInfo>();
			var fontsXML:XML = XML(evt.target.data);
			
			for each (var fontXML:XML in fontsXML.font){
				var fontVo:FontInfo = FontInfo.parseFromXML(fontXML);
				availableFonts.push(fontVo);
			}
			
			for each(var fn:Function in _fontListLoadedCallback)
				fn();
			_fontListLoadedCallback = null;
		}
		
		public function onFontListReady(fn:Function):void {
			if(availableFonts == null)
				_fontListLoadedCallback.push(fn);
			else
				fn();
		}
		
		public function requireFont(format:TextFormat, onReady:Function):void {
			var fontStyleVo:FontStyleInfo = getFontStyle(format.font, format.bold, format.italic);
			
			if(fontStyleVo)
				fontStyleVo.require(onReady);
		}
		
		public function getFontStyle(name:String, bold:Boolean, italic:Boolean):FontStyleInfo {
			var fontVo:FontInfo = getFont(name);
			
			if(fontVo == null)
				return null;
			
			var fontStyleVo:FontStyleInfo;
			for each(fontStyleVo in fontVo.styles){
				if(bold == fontStyleVo.bold && italic == fontStyleVo.italic)
					return fontStyleVo;
			}
			return null;
		}
		
		public function getFont(name:String):FontInfo {
			for each(var fontVo:FontInfo in availableFonts){
				if(fontVo.name == name)
					return fontVo;
			}
			return null;
		}
	}
}